#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
APP_INSTALL_NAME="maxkb"
APP_TARGET_DIR_NAME="maxkb"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo 'App Dir: '${CURRENT_APP_PATH}

source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/$APP_INSTALL_NAME/env"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/docker_image_util.sh"

gen_image_repo_cpu $_DOCKER_IMAGE_NAME $_DOCKER_IMAGE_NAME_LMD $_DOCKER_IMAGE_TAG
APP_IMAGE_REPO=$APP_IMAGE_REPO_RESULT

cd "$CURRENT_APP_PATH"

CONTAINER_SERVER_PORT=8080
if [ -n "$SERVER_PORT" ]; then
  CONTAINER_SERVER_PORT=$SERVER_PORT
fi

if current_os_is_windows; then
   export MSYS_NO_PATHCONV=1 
fi

# CONTAINER_NAME_OLD="${APP_TARGET_DIR_NAME}-lmdown"
CONTAINER_NAME="${APP_TARGET_DIR_NAME}-lmdown"


stop_and_rm_container() {
  echo "stop container"
  docker stop "$CONTAINER_NAME" 2>/dev/null
  docker rm "$CONTAINER_NAME" 2>/dev/null
}

stop_container_when_exit() {
  echo "stop container"
  export STOP_BY_CODE=1
  
  if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    echo "macOS system."
    docker stop "$CONTAINER_NAME" 2>/dev/null 
  elif current_os_is_windows; then
    echo "Windows system."
    cmd.exe /C "docker stop $CONTAINER_NAME"
  fi
  # docker rm "$CONTAINER_NAME" 2>/dev/null
  # exit 1
}

trap stop_container_when_exit EXIT SIGINT SIGTERM SIGHUP SIGQUIT

check_and_start_container() {
  if [ "$(docker ps -a -f "name=$CONTAINER_NAME" --format "{{.Status}}")" ]; then
    echo "$CONTAINER_NAME is running"
    echo "stop $CONTAINER_NAME and run it."
    stop_and_rm_container
    # echo "show logs: $CONTAINER_NAME "
    # docker logs -f -n 100 $CONTAINER_NAME
  else 
    # --gpus all 
    echo "$CONTAINER_NAME is not running. run a new container."
  fi

  docker run -it --name $CONTAINER_NAME \
    -p ${CONTAINER_SERVER_PORT}:8080 -v "${CURRENT_APP_PATH}"/postgresql-data:/var/lib/postgresql/data \
    -v "${CURRENT_APP_PATH}"/python-packages:/opt/maxkb/app/sandbox/python-packages \
    "$APP_IMAGE_REPO"

  exit_code=$?

  if [ $exit_code -ne 0 ]; then
    echo $exit_code
    if [ $STOP_BY_CODE -ne 1 ]; then
      echo "lmdevent:docker_run_error"
    fi
    exit 1
  fi

}

check_and_start_container

